﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.DiaoDongService;
using CommunitySystem.EmpbasicService;
using CommunitySystem.PageView.EmpBasicManager;
using DiaoDongModel = CommunitySystem.DiaoDongService.DiaoDongModel;

namespace CommunitySystem
{
    public partial class DiaoDongWindow : ChildWindow
    {
        private DiaoDongService.DiaoDongModel model = new DiaoDongService.DiaoDongModel();
        private DiaoDongService.DiaoDongServiceClient Client = new DiaoDongService.DiaoDongServiceClient();
        private EmpbasicService.EmpBasicServiceClient empclient = new EmpbasicService.EmpBasicServiceClient();
        public int ID;
        public int OrgID;
        public bool IsNew = false;
        public string SFCK = "";
        public DiaoDongWindow(int orgID, int iD, bool isnew,string shifouchakan,string type)
        {
            InitializeComponent();
            if (type == "外区调入" || type == "外省市调入")
            {
                diaoruxingshi.Visibility = diaoruxingshi1.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                diaoruxingshi.Visibility = diaoruxingshi1.Visibility = System.Windows.Visibility.Collapsed;
            }
            zhiwushuxing.OnSelectionChanged += new OnSelectionChangedEvent(zhiwushuxing_OnSelectionChanged);
            lingdao.Visibility = feilingdao.Visibility = System.Windows.Visibility.Collapsed;
            empclient.GetBianZhiModelCompleted += new EventHandler<EmpbasicService.GetBianZhiModelCompletedEventArgs>(Client_GetBianZhiModelCompleted);
            Client.GetDiaoDongCompleted += new EventHandler<GetDiaoDongCompletedEventArgs>(Client_GetDiaoDongCompleted);
            empclient.GetOrgForHRModelCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(empclient_GetOrgForHRModelCompleted);
            Client.AddDiaoDongCompleted += new EventHandler<AddDiaoDongCompletedEventArgs>(Client_AddDiaoDongCompleted);
            Client.UpdateDiaoDongCompleted += new EventHandler<UpdateDiaoDongCompletedEventArgs>(Client_UpdateDiaoDongCompleted);
            empclient.GetOrgForHRModelAsync(orgID);
            ID = iD;
            OrgID = orgID;
            IsNew = isnew;
            SFCK = shifouchakan;
            empclient.GetBianZhiModelAsync(OrgID.ToString(), 0);
            if (IsNew)
            {
                this.Title = "新增调动信息";
                model = new DiaoDongModel();
                model.Type = type;
                
                this.DataContext = model;
            }
            else
            {
                this.Title = "编辑调动信息";
                
            }
            if(shifouchakan == "查看")
            {
                name.IsEnabled =
                    cardno.IsEnabled =
                    gender.IsEnabled =
                    birthday.IsEnabled = yuandanwei.IsEnabled = yuanbumen.IsEnabled = yuanzhiwei.IsEnabled =
                                                                                      biaoti.IsEnabled =
                                                                                      xianzhiwei.IsEnabled = false;
            }
            else
            {
                name.IsEnabled =
                    cardno.IsEnabled =
                    gender.IsEnabled =
                    birthday.IsEnabled = yuandanwei.IsEnabled = yuanbumen.IsEnabled = yuanzhiwei.IsEnabled =
                                                                                      biaoti.IsEnabled =
                                                                                      xianzhiwei.IsEnabled = true;
            }
        }
        void zhiwushuxing_OnSelectionChanged(object sender, object NewValue, object OldValue)
        {
            if (NewValue != null)
            {
                if (NewValue.ToString() == "领导职务")
                {
                    lingdao.Visibility = System.Windows.Visibility.Visible;
                    feilingdao.Visibility = System.Windows.Visibility.Collapsed;
                }
                if (NewValue.ToString() == "非领导职务")
                {
                    lingdao.Visibility = System.Windows.Visibility.Collapsed;
                    feilingdao.Visibility = System.Windows.Visibility.Visible;
                    model.RQEnd = null;
                    model.SYQ = null;
                }
            }
        }
        void Client_GetBianZhiModelCompleted(object sender, EmpbasicService.GetBianZhiModelCompletedEventArgs e)
        {
            biaoti.ItemsSource = null;
            biaoti.ItemsSource = e.Result;
            if (biaoti.ItemsSource != null)
            {
                for (int i = 0; i < ((ObservableCollection<BianZhiModel>)biaoti.ItemsSource).Count; i++)
                {
                    if (((ObservableCollection<BianZhiModel>)biaoti.ItemsSource)[i].JiGouMingCheng == model.NewPositionName)
                        biaoti.SelectedIndex = i;
                }
            }
            if(!IsNew)
                Client.GetDiaoDongAsync("", ID, "", "", "");
        }
        void gangwei_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                model.NewPositionName = ((BianZhiModel)((((ComboBox)sender).SelectedItem))).JiGouMingCheng;
            }

        }

        void Client_UpdateDiaoDongCompleted(object sender, UpdateDiaoDongCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("编辑成功！");
                this.DialogResult = true;
            }
        }

        void Client_AddDiaoDongCompleted(object sender, AddDiaoDongCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("新增成功！");
                
                this.DialogResult = true;
            }
        }

        private string dengluorg = "";
        void empclient_GetOrgForHRModelCompleted(object sender, EmpbasicService.GetOrgForHRModelCompletedEventArgs e)
        {
            if(e.Result != null && e.Result.Count >0)
                dengluorg = model.NewOrgName = e.Result[0].Name;
        }

        void Client_GetDiaoDongCompleted(object sender, GetDiaoDongCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                model = e.Result[0];
                if (biaoti.ItemsSource != null)
                {
                    for (int i = 0; i < ((ObservableCollection<BianZhiModel>)biaoti.ItemsSource).Count; i++)
                    {
                        if (((ObservableCollection<BianZhiModel>)biaoti.ItemsSource)[i].JiGouMingCheng == model.NewPositionName)
                            biaoti.SelectedIndex = i;
                    }
                }
            }
            //empclient.GetBianZhiModelAsync(OrgID.ToString(), 0);
            this.DataContext = model;
        }

        #region 身份证验证
        private void textBoxCode2_LostFocus(object sender, EventArgs e)
        {
            SetStatus(cardno.Text);
        }
        public void SetStatus(string idcard)
        {
            if (ValiIdCard(idcard))
            {
                model.Gender = Checks.IsMan(idcard) ? "男" : "女";
                gender.Field = "Gender";
                model.Birthday = Convert.ToDateTime(Checks.GetBirthDay(idcard).ToString());
            }
        }
        public static bool IsStringMissing(string value)
        {
            return
                String.IsNullOrEmpty(value) ||
                value.Trim() == String.Empty;
        }
        public static bool ValiIdCard(string idcard)
        {
            if (IsStringMissing(idcard)) return false;
            if (idcard == null || (idcard.Length != 15 && idcard.Length != 18))
            {
                return false;
            }

            if (idcard.Length == 18)
            {
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x|X)$");
                System.Text.RegularExpressions.Match mc = rg.Match(idcard);
                if (!mc.Success)
                {
                    return false;
                }

                if (int.Parse(idcard.Substring(6, 4)) < 1850 || int.Parse(idcard.Substring(6, 4)) > DateTime.Now.Year + 1)
                {
                    return false; // 不允许 1850年以前的日期，以及不允许当前年＋2以后的日期

                }

                try
                {
                    DateTime.Parse(idcard.Substring(6, 4) + "-" + idcard.Substring(10, 2) + "-" + idcard.Substring(12, 2));
                }
                catch
                {
                    return false;
                }

                string idcard15 = idcard.Substring(0, 6) + idcard.Substring(8, 9);

                //if (GetLongIDCardNumber(idcard15) != idcard)
                //{
                //    return false;
                //}

            }
            else if (idcard.Length == 15)
            {
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{15}");
                System.Text.RegularExpressions.Match mc = rg.Match(idcard);
                if (!mc.Success)
                {
                    return false;
                }

                try
                {
                    DateTime.Parse("19" + idcard.Substring(6, 2) + "-" + idcard.Substring(8, 2) + "-" + idcard.Substring(10, 2));
                }
                catch
                {
                    return false;
                }
            }

            string[] aCity = new string[]{null,null,null,null,null,null,null,null,null,null,null,
											 "北京","天津","河北","山西","内蒙古",null,null,null,null,null,
											 "辽宁","吉林","黑龙江",null,null,null,null,null,null,null,
											 "上海","江苏","浙江","安微","福建","江西","山东",null,null,null,
											 "河南","湖北","湖南","广东","广西","海南",null,null,null,
											 "重庆","四川","贵州","云南","西藏",null,null,null,null,null,null,
											 "陕西","甘肃","青海","宁夏","新疆",null,null,null,null,null,
											 "台湾",null,null,null,null,null,null,null,null,null,
											 "香港","澳门",null,null,null,null,null,null,null,null,"国外"};
            if (aCity[int.Parse(idcard.Substring(0, 2))] == null)
            {
                return false;
            }

            return true;
        }
        public static string GetLongIDCardNumber(string idcard)
        {
            //		计算方法
            //		(1)十七位数字本体码加权求和公式
            //			   S = Ai * Wi, i = 2, ... , 18
            //		Y = mod(S, 11)
            //		i: 表示号码字符从右至左包括校验码字符在内的位置序号
            //			   Ai:表示第i位置上的身份证号码字符值

            //					  Wi:表示第i位置上的加权因子
            //							 i: 18 17 16 15 14 13 12 11 10 9 8 7  6 5 4 3 2 1
            //		Wi: 7  9 10  5  8  4  2  1  6 3 7 9 10 5 8 4 2 1
            //		(2)校验码字符值的计算
            //			   Y:      0 1 2 3 4 5 6 7 8 9 10
            //		校验码: 1 0 X 9 8 7 6 5 4 3  2

            if (!ValiIdCard(idcard))
            {
                return null;
            }

            if (idcard.Length == 18)
            {
                return idcard;
            }

            idcard = idcard.Substring(0, 6) + "19" + idcard.Substring(6, 9);

            int[] Wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
            string[] CK = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };

            int sig = 0;
            int i;

            for (i = 0; i < 17; i++)
            {
                sig += Wi[i] * int.Parse(idcard.Substring(i, 1));
            }
            int y = sig % 11;

            for (i = 0; i < 11; i++)
            {
                if (y == i)
                {
                    idcard += CK[i];
                }
            }

            return idcard;
        }
        #endregion
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            //if (string.IsNullOrEmpty(name.Text))
            //{
            //    SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员姓名！");
            //    return;
            //}
            if (Valid())
            {
                model.Status = "未审核";
                if (IsNew)
                {
                    model.RZQMSJ = DateTime.Today;
                    model.NewOrgID = OrgID;
                    Client.AddDiaoDongAsync(model);
                }
                else Client.UpdateDiaoDongAsync(model);
            }
        }

        public bool Valid()
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员姓名！");
                return false;
            }
            if (string.IsNullOrEmpty(model.CardNo))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员证件号码！");
                return false;
            }
            if (string.IsNullOrEmpty(model.Gender))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员性别！");
                return false;
            }
            if (string.IsNullOrEmpty(model.Birthday.ToString()))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员出生日期！");
                return false;
            }
            if (string.IsNullOrEmpty(model.ZWCCSJ.ToString()))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入任现职务层次时间！");
                return false;
            }
            if (string.IsNullOrEmpty(model.ZWSXSJ.ToString()))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入任现职务属性时间！");
                return false;
            }
            if (string.IsNullOrEmpty(model.NewPositionName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员现部门！");
                return false;
            }
            if (string.IsNullOrEmpty(model.NewDutyName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员现职位！");
                return false;
            }
            if (string.IsNullOrEmpty(model.OrgName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员原单位！");
                return false;
            }
            if (string.IsNullOrEmpty(model.DutyName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员原职位！");
                return false;
            }
            if (string.IsNullOrEmpty(model.PositionName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员原部门！");
                return false;
            }
            if (string.IsNullOrEmpty(model.DutyLevel))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员职务层次！");
                return false;
            }
            if (string.IsNullOrEmpty(model.DutyAttribute))
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请输入人员职务属性！");
                return false;
            }
            if (string.IsNullOrEmpty(model.WorkCharge))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员分管（从事）工作！");
                return false;
            }
            return true;
        }

        private string pattern = @"^[0-9]+([.]{1}[0-9]+){0,1}$";
        private void TextBox_LostFocus1(object sender, RoutedEventArgs e)
        {
            Match m = Regex.Match(((TextBox)sender).Text, pattern); // 匹配正则表达式
            if (!m.Success) // 输入的不是数字
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("只能输入数字！");
                ((TextBox)sender).Text = "";
                return;
            }
        }
    }
}
